package com.zahb.qadx.ui.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.UserInfoModel;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.AnswerExercisesActivity;
import com.zahb.qadx.ui.activity.AttentionActivity;
import com.zahb.qadx.ui.activity.MyArchivesActivity;
import com.zahb.qadx.ui.activity.MyBookActivity;
import com.zahb.qadx.ui.activity.MyCertificateActivity;
import com.zahb.qadx.ui.activity.MyChoiceExamActivity;
import com.zahb.qadx.ui.activity.MyCollectionActivity;
import com.zahb.qadx.ui.activity.PerfectArchivyActivity;
import com.zahb.qadx.ui.activity.PersonalActivity;
import com.zahb.qadx.ui.activity.SettingActivity;
import com.zahb.qadx.ui.view.CircleImageView;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.JsonUtil;
import com.zahb.qadx.util.Tips;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by huwei.
 * Data 2020-09-29.
 * Time 09:28.
 */
public class MineFragment extends BaseFragmentExt implements View.OnClickListener {
    private ImageView img_setting, img_notice;
    private CircleImageView img_head;
    private RelativeLayout rl_choice_exam, rl_book, rl_certificate, rl_archives,rl_answer_exercise;
    private TextView tv_collection, tv_attention, tv_name, tv_enterprise;
    private LinearLayout ll_no_role;
    String phone;
    String userName;
    String orgName;
    String idCard;
    List<String> partNames = new ArrayList<>();

    @Override
    protected int getLayout() {
        return R.layout.fragment_my;
    }

    private Gson mGson = new Gson();

    private void updateItemChoiceExam(boolean appAuthorityMenu) {
        rl_choice_exam.setVisibility(appAuthorityMenu ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void initViews(View view) {
        img_setting = view.findViewById(R.id.img_setting);
        rl_answer_exercise=view.findViewById(R.id.rl_answer_exercise);
        rl_answer_exercise.setOnClickListener(this);
        img_setting.setOnClickListener(this);
        img_notice = view.findViewById(R.id.img_notice);
        img_notice.setOnClickListener(this);
        rl_choice_exam = view.findViewById(R.id.rl_choice_exam);
        rl_choice_exam.setOnClickListener(this);
        rl_book = view.findViewById(R.id.rl_book);
        rl_book.setOnClickListener(this);
        rl_certificate = view.findViewById(R.id.rl_certificate);
        rl_certificate.setOnClickListener(this);
        rl_archives = view.findViewById(R.id.rl_archives);
        rl_archives.setOnClickListener(this);
        img_head = view.findViewById(R.id.img_head);
        img_head.setOnClickListener(this);
        tv_collection = view.findViewById(R.id.tv_collection);
        tv_collection.setOnClickListener(this);
        tv_attention = view.findViewById(R.id.tv_attention);
        tv_attention.setOnClickListener(this);
        tv_name = view.findViewById(R.id.tv_name);
        tv_enterprise = view.findViewById(R.id.tv_enterprise);
        ll_no_role = view.findViewById(R.id.ll_no_role);
        ll_no_role.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.rl_choice_exam:{//我的抽奖
                MyChoiceExamActivity.actionStart(getContext());
            }
            break;
            case R.id.rl_book:// 我的错题本
                MyBookActivity.actionStart(getContext());
                break;
            case R.id.rl_certificate:// 我的证书
                //BToast.showText(getContext(), "该功能暂未开发");
                MyCertificateActivity.actionStart(getContext());
                break;
            case R.id.rl_archives://我的档案
                archives();

                break;
            case R.id.img_notice:

                break;
            case R.id.tv_collection://我的收藏
                //BToast.showText(getContext(), "该功能暂未开发");
                startActivity(new Intent(getActivity(), MyCollectionActivity.class));
                break;
            case R.id.ll_no_role:
            case R.id.img_head://个人信息
                intent = new Intent(getActivity(), PersonalActivity.class);
                intent.putExtra("phone", phone);
                intent.putExtra("userName", userName);
                String s = partNames.toString();
                String name = s.replace("[", "").replace("]", "");
                intent.putExtra("orgName", name);
                intent.putExtra("idCard", idCard);
                startActivity(intent);
                break;
            case R.id.tv_attention://我的关注
                startActivity(new Intent(getActivity(), AttentionActivity.class));
                break;
            case R.id.img_setting://设置
                intent = new Intent(getActivity(), SettingActivity.class);
                intent.putExtra("phone", phone);
                intent.putExtra("orgName", orgName);
                intent.putExtra("size", String.valueOf(BaseApplication.getContext().getDataLogin().getOrgList().size()));
                startActivity(intent);
                break;
            case R.id.rl_answer_exercise://练习活动
                startActivity(new Intent(getActivity(), AnswerExercisesActivity.class));
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getAttentionData();
        getAppAuthorityMenu();
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            addDisposable(RetrofitService.getNetService()
                    .getUserInfo()
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        if (response.getStatusCode() == 200) {
                            getUserInfo(response);
                        } else {
                            showBindToast(response.getErrorInfo());
                        }
                    }, throwable -> {
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                    }));
        }
    }

    private void getUserInfo(UserInfoModel response) {
        phone = response.getData().getPhone();
        userName = response.getData().getUserName();
        orgName = response.getData().getOrgName();
        idCard = response.getData().getIdCard();
        tv_enterprise.setText(orgName);
        tv_enterprise.setBackground(getResources().getDrawable(R.drawable.shape_border_black));
        partNames = response.getData().getPartNames();
        tv_name.setText(userName);
    }

    private void getAttentionData() {
        Map<String, Object> params = new HashMap<>();
        params.put("attentioType", "1");
        params.put("pageNo", 1);
        params.put("pageSize", 10);
        params.put("relationId", "");

        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            showProgressDialog("");
            addDisposable(RetrofitService.getNetService()
                    .getUserAttention(body)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        hideProgressDialog();
                        if (response.getStatusCode() == 200) {
                            int total = response.getData().getTotal();
                            tv_attention.setText("我的关注(" + total + ")");
                        }
                    }, throwable -> {
                        hideProgressDialog();
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                    }));
        }
    }

    private void getAppAuthorityMenu() {
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            addDisposable(RetrofitService.getNetService()
                    .getAppAuthorityMenu()
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        Gson gson = JsonUtil.getGson();
                        JsonParser parser = JsonUtil.getParser();
                        String json = gson.toJson(response);
                        JsonObject object = parser.parse(json).getAsJsonObject();
                        if (object.has("statusCode")) {
                            int statusCode = object.get("statusCode").getAsInt();
                            if (statusCode == Constant.CODE_SUCCESS) {
                                if (object.has("data")) {
                                    updateItemChoiceExam(object.get("data").getAsBoolean());
                                }
                            }
                        }
                    }, Throwable::printStackTrace));
        }
    }
    public void archives(){
        addDisposable(RetrofitService.getNetService()
                .archives()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        MyArchivesActivity.archive = response.getData();

                        if (response.getData().getPerfectStatus() == 0) {
                            Intent intent = new Intent(getActivity(), PerfectArchivyActivity.class);
                            //PerfectArchivyActivity   UploadCertificateActivity  WorkExperienceActivity
                            if (response.getData().getInfoVO() != null && !TextUtils.isEmpty(response.getData().getInfoVO().getName())) {
                                intent.putExtra("name", response.getData().getInfoVO().getName());
                            } else {
                                intent.putExtra("name", "");
                            }
                            if (response.getData().getInfoVO() != null && !TextUtils.isEmpty(response.getData().getInfoVO().getPhone())) {
                                intent.putExtra("phone", response.getData().getInfoVO().getPhone());
                            } else {
                                intent.putExtra("phone", "");
                            }
                            startActivity(intent);
                        } else {
                            if (response.getData().getConfigStatus() == 0) {
                                //ToastUtils.s(getActivity(), "企业未配置档案模板，暂时无法查看档案");
                                showBindToast("企业未配置档案模板，暂时无法查看档案");
                                return;
                            }else{
                                MyArchivesActivity.actionStart(getContext());
                            }
                        }

                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());

                }));


    }
}
